package com.example.myproject.Sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.myproject.pojo.User;
import com.example.myproject.session.UserSession;


public class MySqliteOpenHelper extends SQLiteOpenHelper {
    private static final String DB_NAME="MySqlite.db";

    private static final String create_users="create table users(username varchar(32),password varchar(32))";

    public MySqliteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, DB_NAME,null, 1);
    }



    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(create_users);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }

    public long register (User user,Context context){

        SQLiteDatabase db=getWritableDatabase();
        String query = "SELECT count(*) FROM  users  WHERE  username  = ?";
        Cursor cursor = db.rawQuery(query, new String[]{user.getUsername()});
        boolean exists = cursor.getCount() > 0;
        cursor.close();
        if(exists){
            Toast.makeText(context, "用户名已存在，请更换其他用户名。", Toast.LENGTH_SHORT).show();
            return 0;
        }
        ContentValues cv=new ContentValues();
        cv.put("username",user.getUsername());
        cv.put("password",user.getPassword());
        long users=db.insert("users",null,cv);
        return users;
    }


    public boolean login(String username,String password){
        SQLiteDatabase db=getWritableDatabase();
        boolean result=false;
        Cursor users = db.query("users", null, "username like ?", new String[]{username}, null, null, null);
        if(users!=null){
            while (users.moveToNext()){
                String realPassword=users.getString(1);
                result=realPassword.equals(password);
                return result;
            }
        }
        return false;
    }
}
